﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using NewCodeAPI;
using NewCodeAPI.Models;
using NewCodeAPI.Service;

namespace Service
{
    public class RegistrationService
    {
        private readonly EncryptionService _encryptionService;
        public RegistrationService(EncryptionService encryptionService)
        {
            _encryptionService = encryptionService;
        }
        public MsgInfo RegisterUser(string username, string password)
        {

            using (NdlsDBContext context = new NdlsDBContext()) // 创建数据库上下文实例
            {
                //SmPerson user = context.SmPerson.OrderBy(u => u.Username == username).FirstOrDefault();
                //var user = context.SmPerson.FirstOrDefault(u => u.Username == username);
                //if (user != null)
                //{
                //    return new MsgInfo { Status = "Error", Msg = "用户名已存在" };
                //}
                //else
                //{
                    // 使用AES128、CBC模式和PKCS7填充来加密密码
                    string Password = _encryptionService.Encrypt(password);

                    SmPerson userOne = new SmPerson();
                    userOne.Username = username;
                    userOne.Password = Password;
                    userOne.Role = "1";
                    //try
                    //{
                        // 将用户对象添加到数据库
                        context.Add<SmPerson>(userOne);
                        context.SaveChanges(); // 保存更改到数据库
                        return new MsgInfo { Status = "Success", Msg = "注册成功" };
                    //}
                    //catch
                    //{
                    //    return new MsgInfo { Status = "Error", Msg = "注册失败" };
                    //}
                //}
            }
        }
    }
}
